package com.tuo.task;

import com.tuo.beans.Record;
import com.tuo.service.RecordService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.List;

/**
 * Created by tuo on 2016/1/11.
 */
@Component
public class DailyTask {
    @Autowired
    RecordService recordService;

    @Scheduled(cron = "0 0/5 * * * ?")
    public void dailyTask() {
        List<Record> records = null;
        try {
            records = this.recordService.query(new Record());
        } catch (Throwable throwable) {
            throwable.printStackTrace();
        }
        if ((records != null ? records.size() : 0) == 0) {
            Record record = new Record();
            record.setLastTime(System.currentTimeMillis());
            try {
                this.recordService.task();
                record.setUpdated(true);
            } catch (Throwable e) {
                record.setUpdated(false);
            }
            try {
                this.recordService.save(record);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        } else {
            Record record = records.get(0);
            boolean isSameDay = true;
            {
                Calendar last = Calendar.getInstance();
                last.setTimeInMillis(record.getLastTime());
                Calendar now = Calendar.getInstance();
                now.setTimeInMillis(System.currentTimeMillis());
                isSameDay = (last.get(Calendar.YEAR) == now.get(Calendar.YEAR)) && (last.get(Calendar.MONTH) == now.get(Calendar.MONTH)) && (last.get(Calendar.DAY_OF_YEAR) == now.get(Calendar.DAY_OF_YEAR));
            }
            if (isSameDay) {
                return;
            }
            record.setLastTime(System.currentTimeMillis());
            try {
                this.recordService.task();
                record.setUpdated(true);
            } catch (Throwable e) {
                record.setUpdated(false);
            }
            try {
                this.recordService.update(record);
            } catch (Throwable throwable) {
                throwable.printStackTrace();
            }
        }
    }
}
